#include "../inc/thermometer_device.h"
#include "stdio.h"

#define SET_SENSOR_HUMIDITY(x, v) ((x)->num_data[0] = v)
#define SET_SENSOR_TEMPERATURE(x, v) ((x)->num_data[1] = v)
#define GET_SENSOR_HUMIDITY(x) ((x)->num_data[0])
#define GET_SENSOR_TEMPERATURE(x) ((x)->num_data[1])
static e_device_err cc_thermometer_read_cb(void *user_data, const char *msg, int type,
                                           void *data)
{
  cc_log_d("cc_thermometer_read_cb\r\n");
  user_device_t dev = (user_device_t)user_data;
  // sensors_event_t event;
  // DHT_Unified *sensor = (DHT_Unified *)dev->hard_drv;
  // sensor->temperature().getEvent(&event);
  // while (isnan(event.temperature))
  // {
  //   cc_log_e("read temp failed try again...\r\n");
  //   delay(100);
  //   sensor->temperature().getEvent(&event);
  // }

  // sensor->humidity().getEvent(&event);
  // while (isnan(event.relative_humidity))
  // {
  //   cc_log_e("read humidity failed try again...\r\n");
  //   delay(100);
  //   sensor->humidity().getEvent(&event);
  // }
  // SET_SENSOR_HUMIDITY(dev, event.relative_humidity);
  // SET_SENSOR_TEMPERATURE(dev, event.temperature);
  float *value = (float *)data;
  value[0] = dev->num_data[0];
  value[1] = dev->num_data[1];

  cc_log_d("read data:t:%.2f h:%.2f\r\n", GET_SENSOR_TEMPERATURE(dev),
         GET_SENSOR_HUMIDITY(dev));
  return DEVICE_EOK;
}
static e_device_err cc_thermometer_write_cb(void *user_data, const char *msg,
                                            int type, void *data)
{
  cc_log_d("cc_thermometer_write_cb\r\n");
  return DEVICE_EOK;
}
static e_device_err cc_thermometer_control_cb(void *user_data, const char *msg,
                                              int type, void *data)
{
  cc_log_d("cc_thermometer_control_cb\r\n");
  return DEVICE_EOK;
}

e_device_err cc_thermometer_init(void *device)
{
  user_device_t dev = (user_device_t)device;
  cc_log("cc_thermometer_init_cb:%p\r\n", dev);
  dev->hard_drv = new DHT_Unified(dev->pin[0], DHT11);
  DHT_Unified *sensor = (DHT_Unified *)dev->hard_drv;
  sensor->begin();
  dev->control_cb = cc_thermometer_control_cb;
  dev->read_cb = cc_thermometer_read_cb;
  dev->write_cb = cc_thermometer_write_cb;
  cc_log("cc_thermometer_init success:%p\r\n", dev);
  return DEVICE_EOK;
}
CC_DEVICE_INIT_MOUNT(cc_thermometer_init, CC_DEVICE_TYPE_THERMOMETER)
